package com.easpeed.elevator.utils

import android.annotation.SuppressLint
import com.blankj.utilcode.util.ToastUtils
import com.easpeed.comon.database.DataBaseUtils
import com.easpeed.elevator.BuildConfig
import java.io.PrintWriter
import java.io.StringWriter
import java.io.Writer


class MyUncaughtExceptionHandler : Thread.UncaughtExceptionHandler {

    var default: Thread.UncaughtExceptionHandler? = null

    init {
        default = Thread.getDefaultUncaughtExceptionHandler()
    }

    override fun uncaughtException(t: Thread, ex: Throwable) {
        ex.printStackTrace()
//        ToastUtils.showShort(ex.message+"程序出现错误即将退出")
        val result = saveCrashInfoFile(ex)
        if (BuildConfig.DEBUG) {
            ToastUtils.showLong("程序出现错误即将退出\n $result")
        }
        try {
            setCrashInfo()
            Thread.sleep(3000)
        } catch (e: Exception) {
        }
        default?.uncaughtException(t, ex)
    }

    private fun setCrashInfo() {
    }

    /**
     * 保存错误信息到文件中
     * @param ex
     * @return 返回文件名称,便于将文件传送到服务器
     * @throws Exception
     */
    @SuppressLint("SimpleDateFormat")
    private fun saveCrashInfoFile(ex: Throwable): String? {
        val sb = StringBuffer()
        try {
            val writer: Writer = StringWriter()
            val printWriter = PrintWriter(writer)
            ex.printStackTrace(printWriter)
            var cause = ex.cause
            while (cause != null) {
                cause.printStackTrace(printWriter)
                cause = cause.cause
            }
            printWriter.flush()
            printWriter.close()
            val result: String = writer.toString()
            sb.append(result)
            //崩溃日志保存到数据库中
            DataBaseUtils.saveCrashLog("", sb.toString())
            return sb.toString()
        } catch (e: Exception) {
        } finally {
        }
        return null
    }

}